<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/9/16 21:09
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Role_Model extends ADM_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取一条记录
     * @param $itemId
     * @return bool
     */
    public function getItem($itemId)
    {
        if ($itemId == 0 || $itemId == 1) {
            return false;
        }

        $q = $this->db->where('id', $itemId)->get('admin_role');
        return $q->row_array();
    }

    /**
     * 获取所有角色
     * @return mixed
     */
    public function getRoles()
    {
        $q = $this->db->order_by('id', 'DESC')->get('admin_role');
        return $q->result_array();
    }

    /**
     * 保存
     * @param $roleName
     * @param array $roles
     * @return bool
     */
    public function save($roleName, Array $roles)
    {
        if (empty($roleName) || empty($roles)) {
            return false;
        }

        $roles = $this->_formatRoles($roles);
        $this->db->insert('admin_role', [
            'role' => $roleName,
            'value' => json_encode($roles),
            'created_time' => date('Y-m-d H:i:s')
        ]);

        return $this->db->insert_id();
    }

    /**
     * 修改
     * @param $roleId
     * @param $roleName
     * @param array $roles
     * @return bool
     */
    public function edit($roleId, $roleName, Array $roles)
    {
        if (empty($roleId) || empty($roleName) || empty($roles)) {
            return false;
        }

        $roles = $this->_formatRoles($roles);
        return $this->db->where('id', $roleId)->update('admin_role', [
            'role' => $roleName,
            'value' => json_encode($roles),
        ]);
    }

    /**
     * 格式化
     * @param $roles
     * @return array
     */
    public function _formatRoles($roles)
    {
        $newRoles = [];
        foreach ($roles as $item) {
            $newRoles[] = intval($item);
        }
        return array_unique($newRoles);
    }

}
